﻿	$(document).on("click", '.clickimg', function () {
	    $(this).toggleClass("on");
	});
	pushHistory();

	window.addEventListener("popstate", function (e) {
        if($(".clickimg.on").length!=0){
//            e.preventDefault();
//            $(".clickimg.on").trigger("click");
	    window.location = document.referrer;
        }
	}, false);

	function pushHistory() {
	    var state = {
	        title: "title",
	        url: ""
	    };
	    window.history.pushState(state, "title", "");
	}
    

	var house_img = document.getElementById("house_img");
	var code_img = document.getElementById("code");

	$.fn.imgupload=function(){
		if(typeof FileReader === 'undefined') {
			result.innerHTML = "抱歉，你的浏览器不支持 FileReader";
		} else {
			if($(this).length!=0) {
				$.each($(this), function(i,v) {
					v.addEventListener('change', readFiledes, false);
				});
			}

		}
	}

	function readFiledes() {
		var new_img, img, del;
		//var formData = new FormData();
		var $that = $(this),ajaxIndex=0;
        var input='<input type="hidden" name="imgNull" id="" value="" placeholder="请耐心等待图片上传！" datatype="*" nullmsg="请耐心等待图片上传！">';
        if($that.parents("form").find("input[name=imgNull]").length==0){
            $that.after(input);
        }
		for(var i = 0; i < this.files.length; i++) {
            console.log(this.files[i]);
         if(this.files[i].size<=(10*1024*1024)){
			var reader = new FileReader();
			reader.readAsDataURL(this.files[i]);
			//formData.append("file", this.files[i]);

			reader.onload = function(e) {
				$that.parent().next(".img_note").css("display", "none");
				
				//	new_img = document.createElement('div');
				new_img = $("<div style='position:relative;'>");
				new_img.attr('class', 'new_img on');

				img =  $("<img>");
				img.attr("src", this.result);

//				del = document.createElement('i');
//				del.setAttribute('class', 'iconfont icon-shanchu1')
                
                del=$('<i class="iconfont icon-guanbi"></i>');
                    
				del[0].onclick = function() {
					$(this).css("display", "none");
					$(this).parent().remove();
                    var aw=[];
                    $that.parent().parent().find(".new_img img").each(function(i,v){
                       if($(v).attr("data-url")!=""&&!!$(v).attr("data-url")){
							 aw.push($(v).attr("data-url"));
                            }
						});
						var strs=aw.join("|");
                        $that.parents(".imgmain_container").find(".upimg_box i").removeClass("icon-fabu").addClass("icon-jiahao1");
                    $that.removeAttr("disabled");
						$that.parent().find(".i_id").val(strs);
				}

				new_img.append(del);
				new_img.append(img);
				console.log($('.code_wrap').children('div'));
				if($that.parent().parent().attr('class').indexOf("house_wrap") > 0) {
					console.log();
					if($that.parent().parent().find('div.new_img').length >= 9) {
						toggleAlert('图片个数个数已达上限！');
						return false;
					}

				} else if($that.parent().parent().attr('class').indexOf("code_wrap") > 0){
					if($that.parent().parent().find('div.new_img').length >= 1) {
						toggleAlert('图片个数个数已达上限！');
						return false;
					} 
				}else{
					if($that.parent().parent().find('div.new_img').length >= 1) {
						toggleAlert('图片个数个数已达上限！');
						return false;
					}
				}
				$that.parent().before(new_img);
                $that.parents(".imgmain_container").find(".upimg_box i").removeClass("icon-jiahao1").addClass("icon-fabu");
                $that.attr("disabled","disabled");
                $that.parents("form").find("input[name=imgNull]").removeAttr("value");
　　　　　　　　　　　　　　
			}
        }else{
            toggleAlert("请选择小于10m的图片！")
        }
		}
        var flAw=this.files.length-1,fl=this.files;
            var ajax=function(aw,index){
               if($that.parent().parent().attr('class').indexOf("house_wrap") > 0) {
					if($that.parent().parent().find('div.new_img').length >= 9) {
						toggleAlert('图片个数个数已达上限！');
						return false;
					}

				} else if($that.parent().parent().attr('class').indexOf("code_wrap") > 0){
					if($that.parent().parent().find('div.new_img').length >= 1) {
						toggleAlert('图片个数个数已达上限！');
						return false;
					} 
				}else{
					if($that.parent().parent().find('div.new_img').length >= 1) {
						toggleAlert('图片个数个数已达上限！');
						return false;
					}
				}
                if(fl[index].size>(10*1024*1024)){
                    return false;
                   }
                var formData = new FormData();
                formData.append("file", fl[index]);
                $.ajax({
                    type: "POST",
                    url: 'http://www.caizhanzhushou.com/index.php?g=Wechat&m=webzhuan&a=ajax',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(res) {
                        var aw=[];
                        var data=res.slice(0,res.length-1);
                        if(fl.length==1){
                            $that.parent().parent().find('.new_img').last().find("img").attr("data-url",data);
                            $that.parent().parent().find('.new_img').last().removeClass("on");
                        }else{
                             $that.parent().parent().find('.new_img').eq(index).find("img").attr("data-url",data);
                        }
                        
            //						img_des_arr.push(res.data.url);
                        $that.parent().parent().find(".new_img img").each(function(i,v){
                            if($(v).attr("data-url")!=""&&!!$(v).attr("data-url")){
                             aw.push($(v).attr("data-url"));
                            }
                        });
                        var strs=aw.join("|");
                        $that.parent().find(".i_id").val(strs);
                        //alert(strs+"--------"+strs.split("|").length)
                        $that.parents("form").find("input[name=imgNull]").val("1");
                        $that.parents(".imgmain_container").find(".upimg_box i").removeClass("icon-fabu").addClass("icon-jiahao1");
                        $that.removeAttr("disabled");
                        if(flAw-ajaxIndex>0){
                            ajaxIndex++;
                            ajax(fl,ajaxIndex);
                        }
                    }
                });
            }

			ajax(fl,ajaxIndex);	
	}
        var imgRem=function(self) {
                    var aw=[];
                    $(self).parent().parent().find(".new_img").not(".eds").find("img").each(function(i,v){
                       if($(v).attr("data-url")!=""&&!!$(v).attr("data-url")){
							 aw.push($(v).attr("data-url"));
                            }
						});
                    var strs=aw.join("|");
                    $(self).parent().parent().find(".i_id").val(strs);
                    $(self).parents(".imgmain_container").find(".upimg_box i").removeClass("icon-fabu").addClass("icon-jiahao1");
                    $(self).parents(".imgmain_container").find("input[type=file]").removeAttr("disabled");
                    setTimeout(function(){
                            $(self).css("display", "none");
                            $(self).parent().remove();
                    },50);
				}
//验证码倒计时插件
 var toggleAlert=function(msg){
    $(".alertMsg").addClass("on").find("span").html(msg);
    var jj=null;
     setTimeout(function(){
        $(".alertMsg").removeClass("on");
    },2000);
};
var fsMsg=function(){};
fsMsg.prototype={
	init:function(json){
		this.obj=null;
		this.num=json.num||60;
		this.tin=null;
		this.bind(json);
        this.json=json;
        window.fsMsgType=false;
//        $("form input[type=submit]").on("click touchstart",function(){
//            if(!window.fsMsgType){
//               toggleAlert("短信验证码为空或错误！");
//               return false;
//               }
//        });
        $(".fsgNull").remove();
          $("form input[type=submit]").each(function(i,v){
              $(v).before('<input type="hidden" name="fsgNull" class="fsgNull" value="" datatype="*" nullmsg="请输入正确的短信验证码！">');
          })
        return this;
	},
	bind:function(json){
		var self=this;
		$(document).on("click touchstart",json.class,function(){
//            window.fsMsgType="true";
            $(this).parents("form").find(".fsgNull").val(1);
			//写接口
			self.obj=$(this)[0];
			if(!$(this).hasClass("on")&&self.bindInput(json)){
				clearInterval(self.tin);
                var tel=self.input.val();
                 $.get('http://www.caizhanzhushou.com/index.php?g=Wechat&m=Common&a=send&num='+tel,function(data){
                         self.tate=data;
//                        this.input.data
                     self.bindSubmit();
                 });
				self.tin=setInterval(function(){
					self.autoplay(json);
				},1000);
				$(this).addClass("on");
			}
            $(".submitAction").removeClass("submitAction");
            $(self.obj).parents("form").find("input[type=submit]").addClass("submitAction");
		});
	},
	bindInput:function(json){
        var self=this;
		this.input=$(self.obj).parents("form").find(json.input);
		var reg = /^1[3578]\d{9}$/;
		if(this.input.val()!=""){
			if(reg.test(this.input.val())){
				return true;
			}else{
				toggleAlert("手机号错误");
				return false;
			}
		}else{
			toggleAlert("手机号不能为空");
			return false;
		}
		return false;
	},
    bindSubmit:function(){
        var self=this,json=this.json;
        //$(self.obj).parents("form").off("submit");
        $(document).on("click",".submitAction",function(e){
            self.code=$(self.obj).parents("form").find(json.code).val();
            if(self.code!=self.tate){
                toggleAlert("验证码错误");
                $(this).attr("readonly","readonly");
                return false;
            }else{
                 $(this).removeAttr("readonly");
            }
        });
    },
	autoplay:function(json){
        var self=this;
		this.num--;
		if(this.num>=0){
			this.obj.style.color="red";
			this.obj.innerHTML=this.num+"s后重发";
			
		}else{
			this.obj.style.color="red";
			this.obj.innerHTML="重新发送验证码";
			$(this.obj).removeClass("on");
			this.obj.disabled=false;
			clearInterval(self.tin);
			this.num=json.num||60;
		}
	}
}
var fsTime=new fsMsg();
        //时间格式化
        Date.prototype.Format = function(fmt) { //author: meizz 
          var o = { 
            "M+" : this.getMonth()+1,                 //月份 
            "d+" : this.getDate(),                    //日 
            "h+" : this.getHours(),                   //小时 
            "m+" : this.getMinutes(),                 //分 
            "s+" : this.getSeconds(),                 //秒 
            "q+" : Math.floor((this.getMonth()+3)/3), //季度 
            "S"  : this.getMilliseconds()             //毫秒 
          }; 
          if(/(y+)/.test(fmt)) 
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
          for(var k in o) 
            if(new RegExp("("+ k +")").test(fmt)) 
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); 
          return fmt; 
            }
       var getCountDown=function(timestamp) {
                var nowTime = new Date();
                var endTime = new Date(timestamp * 1000);
            
                var t = endTime.getTime() - (nowTime.getTime()-(3600*24*15*1000));
//                var d=Math.ceil(t/1000/60/60/24);
                var d=Math.floor(t/(1000 * 60 * 60 * 24))+1;
                var hour = Math.floor(t / 1000 / 60 / 60 % 24);
                var min = Math.floor(t / 1000 / 60 % 60);
                var sec = Math.floor(t / 1000 % 60);

                if (hour < 10) {
                    hour = "0" + hour;
                }
                if (min < 10) {
                    min = "0" + min;
                }
                if (sec < 10) {
                    sec = "0" + sec;
                }
                var countDownTime =d>0?"转介信息"+d+"天后自动失效":"已失效";
               return countDownTime;
       }
    //城市联动
    $.fn.selectCity=function(self,indexs){

        var  collCities = [['选择城区']

                            ,['新城区','碑林区','莲湖区','灞桥区','未央区','雁塔区','阎良区','临潼区','长安区','其它区']
                            ,["锦江区","青羊区","金牛区","武侯区","成华区","龙泉驿区","青白江区","新都区","温江区","其它区"]
                            ,["中原区","二七区","管城回族区","金水区","上街区","惠济区","中牟县","巩义市","荥阳市","新密市","新郑市","登封市","郑东新区","高新区","其它区"]
                            ,["江岸区","江汉区","硚口区","汉阳区","武昌区","青山区","洪山区","东西湖区","汉南区","蔡甸区","江夏区","黄陂区","新洲区","其他区"]];

    //                var arr = {"beijing":['海淀区','朝阳区','东城区','西城区']};

        //获取两个下拉菜单对象。 
        var oSelNode = self;
        var oSubSelNode = $(this)[0];

        //获取到底选择的是哪个省。
        var index = indexs||oSelNode.selectedIndex;

        //通过角标到容器去获取对应的城市数组。
        var arrCities = collCities[index];

        //将子菜单中的内容清空一下。
    //                for(var x=0;x<oSubSelNode.options.length; ){
    //                    oSubSelNode.removeChild(oSubSelNode.options[x]);
    //                }

        //清除动作
        oSubSelNode.length = 0;


        //遍历这个数组。并将这个数组的元素封装成option对象，添加到子菜单中
        for(var x=0; x<arrCities.length; x++){
            var oOptNode = document.createElement("option");
            oOptNode.innerHTML = arrCities[x];
            oOptNode.value=arrCities[x];
            oSubSelNode.appendChild(oOptNode);
        }

    }

   var imgzy=function(img){
        var src=false;
       if(!!img){
        if(img.indexOf("|")!=-1){
            src=img.split("|")[0];
        }else{
            src=img;
        }
        }
        return src;
    }
   var strHref=function(){
       var url=document.URL;
       var start=url.indexOf("#")+1;
       var stop=url.length;
       var str=url.substring(start,stop) 
        if(url.indexOf("#")!=-1){
            setTimeout(function(){
                $("[data-id="+str+"]").trigger("click");
            },15);
           
         }
   }
   
   $.fn.selectSelected=function(){
       var self=$(this);
       $(this).each(function(i,v){
           var val=$(v).attr("value");
           $(v).find("option").each(function(si,sv){
               if($(sv).val()==val){
               if($(v).attr("name")=="chengshi"){
                   $(v).next('select').selectCity(v,si);
                }
                  $(sv).prop("selected",true);
                }  
           });
       });
   }
   
   //锚链接跳转
   $(function(){
       strHref();

   });